package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"git.oschina.net/open-chart/server/models"
	"github.com/shxsun/jas"
)

type V1 struct{}

func (*V1) PostUpdateDesc(ctx *jas.Context) {
	path := ctx.RequireString("path")
	unit := ctx.RequireString("unit")
	low := ctx.RequireInt64("low")
	high := ctx.RequireInt64("high")
	desc := models.Description{
		Path:     path,
		UnitName: unit,
		Low:      int(low),
		High:     int(high),
	}
	err := models.UpdateDescription(desc)
	if err != nil {
		ctx.Error = jas.NewRequestError(err.Error())
	}
}

func (*V1) PostAdd(ctx *jas.Context) {
	path := ctx.RequireString("path")
	value := ctx.RequireInt64("value")
	err := models.AddRecord(path, int(value))
	if err != nil {
		ctx.Error = jas.NewRequestError(err.Error())
	}
}

func (*V1) GetRecords(ctx *jas.Context) {
	path := ctx.RequireString("path")
	back := time.Duration(time.Hour * 24 * -1) // a day ago
	from := ctx.Default(time.Now().Add(back).UnixNano()).RequireInt64("start")
	//t := time.Unix(from/int64(time.Second), from %int64(time.Second))
	data, err := models.GetRecords(path, from)
	if err != nil {
		ctx.Error = jas.NewRequestError(err.Error())
		return
	}
	ctx.Data = data
}

// breadcrumb
func (*V1) GetBreadcrumb(ctx *jas.Context) {
	ctx.Data = models.GetChain()
}

func main() {
	addr := ":8011"
	fmt.Println("listen on " + addr + " ...")
	models.CreateDb()
	router := jas.NewRouter(new(V1))
	router.BasePath = "/api/"
	fmt.Println(router.HandledPaths(true))
	http.Handle(router.BasePath, router)
	http.Handle("/", http.FileServer(http.Dir("./")))

	err := http.ListenAndServe(addr, nil)
	if err != nil {
		log.Fatal(err)
	}
}
